package servlet;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.simple.JSONObject;
import connection.DbConnection;

import response.DeviceInterface;

import model.CAIImpl;
import model.PollImpl;
import model.ResponseImpl;
import model.TimerImple;
import bean.Poll;
import bean.PollUser;
import bean.Question;
import model.EmailingSystem;

public class CAIServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5830923201054710022L;
	
	static DbConnection conn = new DbConnection();

	public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			conn.close();
		}catch(Exception e){
			System.out.println("error closing conn in doPost of caiservlet");
		}
		conn = new DbConnection();
		String qID = request.getParameter("questionid");
		String setState = request.getParameter("setstate");//1 if we want to toggle question state, else 0
		String optionid = request.getParameter("optionid");
		
		int status = -1;
		int correct = -1;
		String option = "";
		int QuestionID = -1;
		try{
			QuestionID = Integer.parseInt(request.getParameter("questionid"));
		}catch(Exception e){
			System.out.println("Exception! "+Integer.toString(QuestionID));	
		}
		
		CAIImpl ci = new CAIImpl();
		
		//toggle state
		if(setState.equals("1")){
			ci.toggleState(QuestionID, setState);
		}
		
		//get option's correct bool
		if(!(optionid.equals("-1"))){
			if(ci.getCorrect(QuestionID, optionid)){
				correct = 1;
			}else{
				correct = 0;
			}
		}
		
		//get state
		status = ci.getState(QuestionID);	
		
		System.out.println("qID:"+qID);
		try{
			JSONObject obj = new JSONObject();
			obj.put("status", status);
			obj.put("optionid", optionid);
			obj.put("correct", correct);
			System.out.println("status:"+status);
			response.getWriter().print(obj);
			response.getWriter().flush();
		}catch(Exception e){
			System.out.println("setQuestionState: Problem's here!");
		}
	}
	
	
}
